package com.personalblog.handler.apiExceptionHandler;

import com.personalblog.handler.ApiException;
import lombok.Getter;
import lombok.Setter;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jxau_scf
 * @date 2021/3/22 - 10:23
 */
@ControllerAdvice
public class ApiExceptionHandlerAdvice {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        logger.error("Request URL : {},Exception : {}",request.getRequestURL(),e);

        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }


        ModelAndView mv = new ModelAndView();
        mv.addObject("url", request.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;



    }




    /**
     * Handle exceptions thrown by handlers.
     */
//    @ExceptionHandler(value = Exception.class)
//    @ResponseBody
//    public ResponseEntity<ErrorDTO> exception(Exception exception, HttpServletResponse response) {
//        ErrorDTO errorDTO = new ErrorDTO();
//
//        //api异常
//        if(exception instanceof ApiException){
//            ApiException apiException = (ApiException)exception;
//            errorDTO.setErrorCode(apiException.getErrorCode());
//        }else{//未知异常
//            errorDTO.setErrorCode(0L);
//        }
//        errorDTO.setTip(exception.getMessage());
//        ResponseEntity<ErrorDTO> responseEntity = new ResponseEntity<>(errorDTO,HttpStatus.valueOf(response.getStatus()));
//        return responseEntity;
//    }


}

//@Setter
//@Getter
//class ErrorDTO{
//    private Long errorCode;
//    private String tip;
//}

